package com.ebupt.common.net

import com.ebupt.common.net.config.HeaderIntercepter
import com.ebupt.common.net.config.LocalJar
import com.ebupt.common.net.config.LogIntercepter
import com.ebupt.common.net.config.LogLevel
import com.ebupt.common.net.support.LiveDataFactory
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

object RetrofitManager {

    private val mClient = OkHttpClient.Builder()
        .callTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(10, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .cache(Cache(File("sdcard/catch","child"),1024L))
        .addNetworkInterceptor(LogIntercepter(){
            logLevel(LogLevel.BODY)
        })
        .cookieJar(LocalJar())
        .addNetworkInterceptor(HeaderIntercepter())
        .build()



    private var retrofitBuilder = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(LiveDataFactory())
        .client(mClient)


    private var retrofit: Retrofit? = null//retrofit 请求client



    fun initConfig(baseUrl:String,okClient:OkHttpClient = mClient): RetrofitManager {
        retrofit = retrofitBuilder.baseUrl(baseUrl).client(okClient).build()
        return this
    }

    /**
     * 获取retrofit的Service对象
     * [serviceClazz] 定义的retrofit的service 接口类
     */
    fun <T> getService(serviceClazz: Class<T>): T {
        if (retrofit == null) {
            throw UninitializedPropertyAccessException("Retrofit必须初始化，需要配置baseURL")
        } else {
            return retrofit!!.create(serviceClazz)
        }
    }


}